//
//  DiscoveryDetailViewController.m
//  huashiedu
//
//  Created by oceans on 2018/9/27.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "DiscoveryDetailViewController.h"
#import "HttpRequest.h"

@interface DiscoveryDetailViewController ()

@end

@implementation DiscoveryDetailViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.layoutsArr addObject:_layout];
    [self setupViews];
    [self.view addSubview:self.commentInputTF];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [JRMenuView dismissAllJRMenu];
}

- (void)setupViews {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"详情";
    [self.view addSubview:self.dynamicsTable];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewDynamicsLayout * layout = self.layoutsArr[indexPath.row];
    return layout.height;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.layoutsArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewDynamicsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"NewDynamicsTableViewCell"];
    cell.layout = self.layoutsArr[indexPath.row];
    cell.delegate = self;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [JRMenuView dismissAllJRMenu];
}
#pragma mark - ScollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [JRMenuView dismissAllJRMenu];//收回JRMenuView
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.commentInputTF resignFirstResponder];
}
#pragma mark - NewDynamiceCellDelegate
-(void)DynamicsCell:(NewDynamicsTableViewCell *)cell didClickUser:(NSString *)userId
{
    NSLog(@"点击了用户");
}
-(void)DidClickMoreLessInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    NSIndexPath * indexPath = [self.dynamicsTable indexPathForCell:cell];
    NewDynamicsLayout * layout = self.layoutsArr[indexPath.row];
    layout.model.isOpening = !layout.model.isOpening;
    [layout resetLayout];
    CGRect cellRect = [self.dynamicsTable rectForRowAtIndexPath:indexPath];
    
    [self.dynamicsTable reloadData];
    
    if (cellRect.origin.y < self.dynamicsTable.contentOffset.y + 64) {
        [self.dynamicsTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}
-(void)DidClickGrayViewInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    NSLog(@"点击了灰色区域");
}
-(void)DidClickThunmbInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    NSIndexPath * indexPath = [self.dynamicsTable indexPathForCell:cell];
    NewDynamicsLayout * layout = self.layoutsArr[indexPath.row];
    DynamicsModel * model = layout.model;
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kmoment_like paras:@{@"dynamic_id": model.pid} showProgress:NO successful:^(id  _Nullable result) {
        
        NSString *userid = [NSString stringWithFormat:@"%d", [UserModel shared].loginUser._id];
        NSString *nick = [UserModel shared].loginUser.nickname;
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     userid, @"userid",
                                     nick, @"nick", nil];
        NSMutableArray * newThumbArr = [NSMutableArray arrayWithArray:model.optthumb];
        [newThumbArr addObject:dic];
        model.optthumb = [newThumbArr copy];
        [layout resetLayout];
        [weakself.dynamicsTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } failed:nil];
}
-(void)DidClickCancelThunmbInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    NSIndexPath * indexPath = [self.dynamicsTable indexPathForCell:cell];
    NewDynamicsLayout * layout = self.layoutsArr[indexPath.row];
    DynamicsModel * model = layout.model;
    
    __weak typeof(self) weakself = self;
    [HttpRequest postURL:kmoment_like paras:@{@"dynamic_id": model.pid} showProgress:NO successful:^(id  _Nullable result) {
        
        NSMutableArray * newThumbArr = [NSMutableArray arrayWithArray:model.optthumb];
        [newThumbArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary * thumbDic = obj;
            if ([thumbDic[@"nick"] isEqualToString:[UserModel shared].loginUser.nickname]) {
                [newThumbArr removeObject:obj];
                model.optthumb = [newThumbArr copy];
                [layout resetLayout];
                [weakself.dynamicsTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                *stop = YES;
            }
        }];
    } failed:nil];
    
}
-(void)DidClickCommentInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    NSIndexPath * indexPath = [self.dynamicsTable indexPathForCell:cell];
    self.commentIndexPath = indexPath;
    
    self.commentInputTF.placeholder = @"输入评论...";
    [self.commentInputTF becomeFirstResponder];
    self.commentInputTF.hidden = NO;
}
-(void)DidClickSpreadInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    NSLog(@"点击了推广");
}
- (void)DidClickDeleteInDynamicsCell:(NewDynamicsTableViewCell *)cell
{
    //    WS(weakSelf);
    //    [UIAlertView bk_showAlertViewWithTitle:nil message:@"是否确定删除朋友圈" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
    //        if (buttonIndex == 1) {
    //            NSIndexPath * indexPath = [self.dynamicsTable indexPathForCell:cell];
    //            [SVProgressHUD showSuccessWithStatus:@"删除成功!"];
    //            [weakSelf.dynamicsTable beginUpdates];
    //            [weakSelf.layoutsArr removeObjectAtIndex:indexPath.row];
    //            [weakSelf.dynamicsTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    //            [weakSelf.dynamicsTable endUpdates];
    //        }
    //    }];
}
-(void)DynamicsCell:(NewDynamicsTableViewCell *)cell didClickUrl:(NSString *)url PhoneNum:(NSString *)phoneNum
{
    if (url) {
        if ([url rangeOfString:@"wemall"].length != 0 || [url rangeOfString:@"t.cn"].length != 0) {
            if (![url hasPrefix:@"http://"]) {
                url = [NSString stringWithFormat:@"http://%@",url];
            }
            NSLog(@"点击了链接:%@",url);
        }else{
            [SVProgressHUD showErrorWithStatus:@"暂不支持打开外部链接"];
        }
    }
    if (phoneNum) {
        NSLog(@"点击了电话:%@",phoneNum);
    }
}
#pragma mark - UITextfield Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSInteger commentRow = self.commentIndexPath.row;
    NewDynamicsLayout * layout = [self.layoutsArr objectAtIndex:commentRow];
    DynamicsModel * model = layout.model;
    if (![self.commentInputTF.text isEqualToString:@""]) {
        
        NSString *uniStr = [NSString stringWithUTF8String:[self.commentInputTF.text UTF8String]];
        NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
        NSString *string = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
        
        __weak typeof(self) weakself = self;
        [HttpRequest postURL:kmoment_discuss paras:@{@"dynamic_id": model.pid, @"content": string} showProgress:NO successful:^(id  _Nullable result) {
            
            NSString *userid = [UserModel shared].loginUser.string_id;
            NSString *nick = [UserModel shared].loginUser.nameString;
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithObjectsAndKeys: userid, @"userid", nick, @"nick",
                                         textField.text,@"message",nil,@"touser",nil,@"tonick", nil];//toUserID可能为nil,需放在最后
            NSMutableArray * newCommentArr = [NSMutableArray arrayWithArray:model.optcomment];
            [newCommentArr addObject:dic];
            model.optcomment = [newCommentArr copy];
            [layout resetLayout];
            [weakself.dynamicsTable reloadRowsAtIndexPaths:@[weakself.commentIndexPath] withRowAnimation:UITableViewRowAnimationNone];
            
            weakself.commentInputTF.text = nil;
            [weakself.commentInputTF resignFirstResponder];
        } failed:nil];
    }
    return YES;
}

#pragma mark - getter
-(UITableView *)dynamicsTable
{
    if (!_dynamicsTable) {
        //        _dynamicsTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
        _dynamicsTable = [[UITableView alloc] initWithFrame:CGRectMake(0, XNavigationHeight, ScreenWidth, ScreenHeight - XNavigationHeight - XTabBarHeight) style:UITableViewStylePlain];
        _dynamicsTable.dataSource = self;
        _dynamicsTable.delegate = self;
        _dynamicsTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_dynamicsTable registerClass:[NewDynamicsTableViewCell class] forCellReuseIdentifier:@"NewDynamicsTableViewCell"];
        if ([[[UIDevice currentDevice] systemVersion] compare:@"11.0" options:NSNumericSearch] != NSOrderedAscending) {
            _dynamicsTable.estimatedRowHeight = 0;
        }
        
        UITapGestureRecognizer * tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jjj)];
        
        tableViewGesture.cancelsTouchesInView = NO;
        [_dynamicsTable addGestureRecognizer:tableViewGesture];
    }
    return _dynamicsTable;
}

- (void)jjj {
    [_commentInputTF resignFirstResponder];
}

-(NSMutableArray *)layoutsArr
{
    if (!_layoutsArr) {
        _layoutsArr = [NSMutableArray array];
    }
    return _layoutsArr;
}
-(UITextField *)commentInputTF
{
    if (!_commentInputTF) {
        _commentInputTF = [[UITextField alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 45)];
        _commentInputTF.backgroundColor = COLOR(235, 235, 235, 1);
        _commentInputTF.delegate = self;
        _commentInputTF.textColor = [UIColor blackColor];
        _commentInputTF.returnKeyType = UIReturnKeySend;
    }
    return _commentInputTF;
}

- (void)keyboardWillHide:(NSNotification *)notification{
    
    CGRect frame = _commentInputTF.frame;
    frame.origin.y = self.view.frame.size.height;
    _commentInputTF.frame = frame;
}

- (void)keyboardFrameWillChange:(NSNotification *)notification{
    CGRect keyBoardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect frame = _commentInputTF.frame;
    frame.origin.y = keyBoardFrame.origin.y - 45;
    _commentInputTF.frame = frame;
}

@end
